package org.bjf.modules.sys.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bjf.modules.core.service.BaseService;
import org.bjf.modules.sys.bean.SysUser;
import org.bjf.modules.sys.mapper.SysUserMapper;
import org.bjf.modules.sys.query.SysUserQuery;
import org.bjf.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * @author bjf
 * @date 2017/11/27
 */
@Service
@Slf4j
public class SysUserService extends BaseService<SysUserMapper, SysUser, SysUserQuery> {


    @Autowired
    private RedisUtil redis;

    @Override
    protected LambdaQueryWrapper<SysUser> buildQuery(SysUserQuery q) {
        if (q == null) {
            return null;
        }
        LambdaQueryWrapper<SysUser> qw = new LambdaQueryWrapper<>();
        qw.eq(StringUtils.isNotBlank(q.getUsername()), SysUser::getUsername, q.getUsername());
        qw.eq(StringUtils.isNotBlank(q.getPhone()), SysUser::getPhone, q.getPhone());
        return qw;
    }


    /**
     * 删除用户权限
     */
    @Async
    public void clearUserCache() {
        //===1.删除角色权限缓存
        Set<String> keys = redis.keys("live:rbac:listRolePerm:*");
        for (String key : keys) {
            redis.del(key);
        }

        //===2.清除用户权限缓存
        Set<String> userKeys = redis.keys("live:rbac:hasPerm:*");
        for (String key : userKeys) {
            redis.del(key);
        }

        //===4.清除用户菜单缓存
        Set<String> menuKeys = redis.keys("live:menu:listByUser:*");
        for (String key : menuKeys) {
            redis.del(key);
        }
    }

}
